package cn.parus.service.Impl;

import cn.parus.common.Execption.CustomException;
import cn.parus.common.utils.ExtractCodeUtils;
import cn.parus.entity.FileShareLink;
import cn.parus.mapper.FileShareLinkMapper;
import cn.parus.service.FileShareLinkService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class FileShareLinkServiceImpl extends ServiceImpl<FileShareLinkMapper, FileShareLink> implements FileShareLinkService {

    @Override
    public Page<FileShareLink> searchAllFileShare(String ownerId, Integer current, Integer size) {
        // 参数校验：ownerId 必须存在
        if (StringUtils.isBlank(ownerId)) {
            throw new CustomException("查询文件共享时，用户ID不能为空");
        }

        // 构造查询：只查询当前用户的共享记录
        Page<FileShareLink> page = new Page<>(current, size);
        LambdaQueryWrapper<FileShareLink> queryWrapper = new LambdaQueryWrapper<FileShareLink>()
            .eq(FileShareLink::getOwnerId, ownerId);  // 按文件所有者过滤

        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FileShareLink createNewShareFile(FileShareLink fileShareLink) {
        // 参数校验（保留核心必填字段校验）
        if (fileShareLink == null) {
            throw new CustomException("共享链接对象不能为空");
        }
        if (StringUtils.isBlank(fileShareLink.getFileId())) {
            throw new CustomException("文件ID不能为空（需关联已存在的文件）");
        }
        if (StringUtils.isBlank(fileShareLink.getOwnerId())) {
            throw new CustomException("文件所有者ID不能为空");
        }
        
        // 修改：仅当expireDays存在且<=0时校验（允许null表示永不过期）
        if (fileShareLink.getExpireDays() != null && fileShareLink.getExpireDays() <= 0) {
            throw new CustomException("过期天数必须为正整数（如5天、30天）");
        }

        // 处理过期时间：expireDays存在且>0时计算，否则永不过期（不设置expiresAt）
        if (fileShareLink.getExpireDays() != null && fileShareLink.getExpireDays() > 0) {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime expireTime = now.plusDays(fileShareLink.getExpireDays());
            fileShareLink.setExpiresAt(expireTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        } else {
            // 永不过期时，expiresAt设为null（假设数据库允许null表示永久有效）
            fileShareLink.setExpiresAt(null);
        }

        // 自动装配提取码（生成4位混合码）
        fileShareLink.setExtractCode(ExtractCodeUtils.generateExtractCode());

        // 设置创建时间（格式与过期时间一致）
        fileShareLink.setCreatedAt(LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        try {
            boolean saveResult = save(fileShareLink);
            if (!saveResult) {
                throw new CustomException("共享链接创建失败（数据库保存失败）");
            }
            return fileShareLink;
        } catch (Exception e) {
            throw new CustomException("共享链接创建失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFileShareLink(String fileShareLinkId) {
        if (StringUtils.isBlank(fileShareLinkId)) {
            throw new CustomException("删除链接时，链接ID不能为空");
        }

        FileShareLink existFileShareLink = baseMapper.selectById(fileShareLinkId);
        if(existFileShareLink == null) {
            throw new CustomException("链接不存在，删除失败");
        }

        try {
            baseMapper.deleteById(fileShareLinkId);
        } catch (CustomException e) {
            throw new CustomException("删除失败" + e.getMessage());
        }
    }
}
